package gameserver;

import javax.swing.JTextArea;

/** A class to manage all commands / messages sent to server.
 *  Because Server runs in a loop, it is unresponsive while
 *      operational. This thread must be used to counteract
 *      the loop stall
 */
public class EventInterpreterThread extends Thread {

    public Server server = null;
    public JTextArea CONSOLE = null; // GUI object to print text to

    public EventInterpreterThread() {
        this(null, null);
    }
    public EventInterpreterThread(Server server, JTextArea CONSOLE) {
        super("EventInterpreterThread");
        this.server = server;
        this.CONSOLE = CONSOLE;
    }

    @Override
    public synchronized void start() {
        while (server.mode != SGSGlobal.ENDED) { // loop until server is all done
            while (!server.events.isEmpty()) { // process all incoming messages
                
            }
        }
        // when thread reaches here, it dies
    }


    // Server class should only be used for the game loop
    // All events and actions should be handled in external threads
    /** Read a single game message and act accordingly.
         *  - Perform server-side operations
         *  - Provide output detailing operation success
         */
    public synchronized void processMessage(Data m) {
       guiWriteln("MSG: " + m.data);
    }

    /** Receive a string message from the server console.
     *  Act accordingly and *always* provide console output
     */
    public synchronized void processCommand(String c) {
        if (c == null || server == null) return;
        guiWriteln("> " + c);
        if (c.equals("start")) {
            guiWriteln("Trying to start server.");
            server.mode = SGSGlobal.STARTING;
        } else if (c.equals("end")) {
            // send message to server handler to end loop
            guiWriteln("Trying to end server.");
            server.mode = SGSGlobal.ENDED;
        } else {
            guiWriteln("Unknown command.");
        }
    }

    /** Shutdown the server's sockets.
     *  This does not end the server loop, it only
     *      cleans up sockets so they can be reused
     */
    public synchronized void cleanUpSockets() {
        // have to send a message to the server to stop
        try {
            if (server.serverSocket != null)
                server.serverSocket.close();
        } catch (Exception e) {
            guiWriteln("ERR: cleanUpSockets()");
        }
    }

    /** Write a formatted message to the GUI text area **/
    public synchronized void guiWriteln(String s) {
        CONSOLE.append(s + "\n");
    }
    public synchronized void guiWrite(String s) {
        CONSOLE.append(s);
    }
    public synchronized void guiWriteln() {
        CONSOLE.append("\n");
    }
}
